﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.SharePoint;

namespace DE.Sdc.SharePoint.SPContentStructure.Import
{
    [Serializable]
    [XmlType(AnonymousType = true, Namespace = DeploymentConstants.Namespace)]
    [XmlRoot(ElementName = "Root", Namespace = DeploymentConstants.Namespace, IsNullable = false)]
    public class SPContentStructureImport : Web
    {
        protected static internal bool CurrentContextInitiallySet { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="contentStructureDescriptionXmlPath">Absolute path to the content structure xml file</param>
        /// <param name="receiverProperties">Feature receiver properties</param>
        public static void Import(string contentStructureDescriptionXmlPath, SPFeatureReceiverProperties receiverProperties)
        {
            DeploymentContext.Current.ReceiverProperties = receiverProperties;
            DeploymentContext.Current.ReceiverWeb = DeploymentHelper.GetWeb(receiverProperties.Feature.Parent);
            DeploymentContext.Current.ImportPath = System.IO.Path.GetDirectoryName(contentStructureDescriptionXmlPath);

            Import(contentStructureDescriptionXmlPath);
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="contentStructureDescriptionXmlPath">Absolute path to the content structure xml file</param>
        /// <param name="webUrl">Absolute Url to the Web</param>
        public static void Import(string contentStructureDescriptionXmlPath, string webUrl)
        {
            using (SPSite site = new SPSite(webUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    DeploymentContext.Current.ReceiverWeb = web;
                    DeploymentContext.Current.ImportPath = System.IO.Path.GetDirectoryName(contentStructureDescriptionXmlPath);
                }
            }

            Import(contentStructureDescriptionXmlPath);
        }

        /// <summary>
        /// Starts the content structure import
        /// </summary>
        private static void Import(string contentStructureDescriptionXmlPath)
        {
            try
            {
                SPContentStructureImport contentStructure;
                var serializer = new XmlSerializer(typeof(SPContentStructureImport));
                FileStream importXml = System.IO.File.OpenRead(contentStructureDescriptionXmlPath);

                try
                {
                    contentStructure = (SPContentStructureImport)serializer.Deserialize(importXml);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex.Message, "ContentStructureImporter::Execute:DeserializeXml");
                    throw;
                }
                finally
                {
                    importXml.Close();
                }

                try
                {
                    CurrentContextInitiallySet = SPContext.Current != null;
                    DeploymentContext.Current.Web = DeploymentContext.Current.ReceiverWeb;
                    contentStructure.ImportDefinition(DeploymentContext.Current.ReceiverWeb, DeploymentContext.Current.ReceiverWeb.IsRootWeb ? null : DeploymentContext.Current.ReceiverWeb.ParentWeb);
                    //Web.ImportWeb(contentStructure, DeploymentContext.Current.ReceiverWeb, DeploymentContext.Current.ReceiverWeb.IsRootWeb ? null : DeploymentContext.Current.ReceiverWeb.ParentWeb);
                }
                catch (Exception ex)
                {
                    string message = ex.Message;
                    if (ex.InnerException != null)
                        message += "; " + ex.InnerException.Message + " StackTrace: " + ex.InnerException.StackTrace;
                    Trace.WriteLine(message, "ContentStructureImporter::Execute:ImportWeb");
                    throw;
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                if (ex.InnerException != null)
                    message += "; " + ex.InnerException.Message + " StackTrace: " + ex.InnerException.StackTrace;
                Trace.WriteLine(message, "ContentStructureImporter::Execute:Initialisation");
                throw;
            }
            finally
            {
                DeploymentContext.Reset();
            }
        }
    }
}